<template>
  <h3 style="display: inline-block">{{ title }}</h3>
  <a-button type="primary" size="small" @click="add" style="float: right"
    >新增</a-button
  >
  <a-table
    size="small"
    :columns="columns"
    :dataSource="paramData"
    :pagination="false"
    :bordered="true"
    :scroll="{ y: 200 }"
    :row-selection="{ selectedRowKeys: selectedKeys, onChange: onSelect }"
  >
    <template
      v-for="col in ['name', 'value', 'description']"
      #[col]="{ text, record }"
      :key="col"
    >
      <div>
        <div v-if="editableData[col][record.key]">
          <a-input
            v-model:value="editableData[col][record.key][col]"
            @blur="blur(record, col)"
          />
        </div>
        <div
          v-else
          class="editable-cell-text-wrapper"
          @click="edit(record, col)"
        >
          {{ text }}
        </div>
      </div>
    </template>
    <template #op="{ record }">
      <a-button type="danger" size="small" @click="onDelete(record)"
        >删除</a-button
      >
    </template>
  </a-table>
</template>

<script>
import { CloseOutlined } from "@ant-design/icons-vue";
import { v4 as uuidv4 } from "uuid";

export default {
  name: "ParamTable",
  props: ["title"],
  components: { CloseOutlined },
  data() {
    return {
      columns: [
        {
          title: "名称",
          key: "name",
          dataIndex: "name",
          width: "30%",
          slots: { customRender: "name" },
        },
        {
          title: "值",
          key: "value",
          dataIndex: "value",
          width: "30%",
          slots: { customRender: "value" },
        },
        {
          title: "描述",
          key: "description",
          dataIndex: "description",
          width: "30%",
          slots: { customRender: "description" },
        },
        {
          title: "操作",
          key: "op",
          width: "10%",
          slots: { customRender: "op" },
        },
      ],
      paramData: [],
      editableData: { name: {}, value: {}, description: {} },
      selectedKeys: [],
    };
  },
  methods: {
    edit(record, column) {
      this.editableData[column][record.key] = record;
    },
    blur(record, column) {
      this.editableData[column][record.key] = null;
    },
    onDelete(record) {
      this.paramData = this.paramData.filter((i) => i.key != record.key);
      this.selectedKeys = this.selectedKeys.filter((i) => i != record.key);
    },
    add() {
      const id = uuidv4();
      this.paramData.push({ key: id });
      this.selectedKeys.push(id);
    },
    onSelect(keys) {
      this.selectedKeys = keys;
    },
  },
};
</script>

<style scoped>
.editable-cell-text-wrapper {
  padding: 5px 24px 5px 5px;
}
</style>